package pit.com.ordermobilesystem.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import pit.com.ordermobilesystem.model.Category;
import pit.com.ordermobilesystem.model.Item;
import pit.com.ordermobilesystem.model.Order;
import pit.com.ordermobilesystem.util.OrderConstant;


public class OrderSystemHttpService implements OrderConstant{
	private HttpApi mHttpApi;
	private final String mApiBaseUrl;
	private final static String URL_GET_LIST_CATEGORY = "/resources/category/getcategory";
	private final static String URL_GET_LIST_ITEM = "/resources/item/getitems";
	private final static String URL_SAVE_ORDER = "/resources/order/insorder";
	
	public OrderSystemHttpService(String domain, String port) {
		mApiBaseUrl ="http://" + domain + ":" + port + "/"+NAME_SERVICE;
		mHttpApi = new HttpApiWithAuth();
	}

	private String fullUrl(String url) {
		return mApiBaseUrl + url;
	}
	
	public static String getImageProductURL(String domain, String port, String nameProduct){
		String Url ="http://" + domain + ":" + port + "/"+NAME_SERVICE+"/"+nameProduct;
		return Url;
	}
	
	public Group<Category> downloadCategoryGroup() throws HttpApiException,
	UnsupportedEncodingException, IOException {
	String url = mHttpApi.createHttpRest(
			fullUrl(URL_GET_LIST_CATEGORY));
        Type type = new TypeToken<Group<Category>>(){}.getType();  		
	return (Group<Category>) mHttpApi.doHttpRequest(url,new JSONParser<Category>(type),
			ResponseType.JSON);
	}
	public Group<Item> downloadItemGroup() throws HttpApiException,
	UnsupportedEncodingException, IOException {
	String url = mHttpApi.createHttpRest(
			fullUrl(URL_GET_LIST_ITEM));
        Type type = new TypeToken<Group<Item>>(){}.getType();  		
	return (Group<Item>) mHttpApi.doHttpRequest(url,new JSONParser<Item>(type),
			ResponseType.JSON);
	}
	
	public Response saveOrder(Order order) throws HttpApiException,
	UnsupportedEncodingException, IOException {
	Gson gson=new Gson();
	String order_json = gson.toJson(order);	
	String url = mHttpApi.createHttpRest(
			fullUrl(URL_SAVE_ORDER));
	return (Response) mHttpApi.doHttpRequest(url,order_json,new ResponseParser(),
			ResponseType.JSON);
	}
}
